import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
request.interceptors.request.use(config => {
  const token = store.state.user.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(result => {
  if (result.data instanceof Blob) return result.data
  if (result.data.success) {
    return result.data
  } else {
    Message.error(result.data.message)
    return Promise.reject(result.data.message)
  }
}, error => {
  console.dir(error)
  if (error.response.status === 401) {
    Message.error('验证过期,请重新登陆')
    store.dispatch('user/logout')
    router.push('/login')
  }
  return Promise.reject(error)
})
export default request
